package com.ruoyi.front.service;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.config.WxBean;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;

@Service
public class WeChatServiceImpl implements WeChatService {
    @Autowired
    private  WxMpService wxMpService;
    @Autowired
    private  WxBean weChatProperty;

    @Override
    public void getQr(String state) {
        try {
            ImgUtil.write(getQrImage(state), ImgUtil.IMAGE_TYPE_PNG, ServletUtils.getResponse().getOutputStream());
        } catch (Exception e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
        }
    }

    @Override
    public AjaxResult getQrData(String state) {
        return AjaxResult.success(ImgUtil.toBase64DataUri(getQrImage(state), ImgUtil.IMAGE_TYPE_PNG));
    }

    @Override
    public AjaxResult userInfo(String code, String state) {
        try {
            WxMpOAuth2AccessToken token = getToken(code);
            WxMpUser userInfo = wxMpService.oauth2getUserInfo(token, null);
            return AjaxResult.success(userInfo);
        } catch (WxErrorException e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
        }
        return AjaxResult.error("10001");
    }

    /**
     * 获取token信息
     *
     * @param code code
     * @return token信息
     */
    private WxMpOAuth2AccessToken getToken(String code) {
        try {
            return wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            System.out.println(ExceptionUtils.getStackTrace(e));
        }
        return null;
    }

    /**
     * 获取鉴权地址
     *
     * @param scope 鉴权类型
     * @param state state
     * @return 扫码鉴权地址
     */
    private String getRedirectUrl(String scope, String state) {
        return wxMpService.oauth2buildAuthorizationUrl(getCallbackUrl(), scope, state);
    }

    /**
     * 获取回调地址
     *
     * @return 回调地址
     */
    private String getCallbackUrl() {
        return weChatProperty.getDomain() + weChatProperty.getRedirectUrl();
    }

    /**
     * 获取验证二维码图片
     *
     * @param state state
     * @return 图片
     */
    private BufferedImage getQrImage(String state) {
        return QrCodeUtil.generate(getRedirectUrl(WxConsts.OAuth2Scope.SNSAPI_USERINFO, state),
                QrConfig.create()
                        .setWidth(300)
                        .setHeight(300));
    }
}

